#!/usr/bin/perl
####################################################################
#   Project : Bid Manager
#        ID : $Id$
#   Purpose : Transcoding helper script, especially useful for mediatomb
#    Author : Grzegorz 'Jabbas' Dzięgielewski
####################################################################

use warnings;
use strict;

use Data::Dumper;

# TODO streams checking
# TODO audio resampling

my $preferences = {
    'mencoder_path'         => '/usr/bin/mencoder',
    'mplayer_path'          => '/usr/bin/mplayer',
    'mencoder_threads'      => 8,
    'video_codec'           => 'mpeg2video',
    'video_bitrate'         => 4096,
    'video_framerate'       => 25,
    'audio_codec'           => 'copy',
#    'audio_samplerate'     => '48000',
#    'audio_channels'       => 2,
    'subtitle_codepage'     => 'CP1250',
    'subtitle_ass_style'    => '/home/jabbas/.config/smplayer/styles.ass',
    'output_format'         => 'mpeg',
    'output_options'        => 'format=dvd',
    'additional_options'    => '-really-quiet'
};

my @subtitle_ext = qw/
    txt
    sub
    srt
    ssa
    ass
/;

###############################################################################
######### DO NOT EDIT BELOW THIS IF YOU DON'T KNOW WHAT YOU ARE DOING #########
###############################################################################

($preferences->{'file_input'}, $preferences->{'file_output'}) = @ARGV;

my $opts = generate_options($preferences);

mediainfo($opts);

#transcode($opts);


##### Functions
####################

#mplayer -really-quiet -vo null -ao null -frames 0 -identify /media/multimedia/Filmy/Man\ Of\ The\ Year.mkv 2>/dev/null
sub mediainfo {
    my $opts = shift;
    
    my @mplayer_exec = (
        $preferences->{'mplayer_path'},
        quotemeta $preferences->{'file_input'},
        '-vo'           , 'null',
        '-ao'           , 'null',
        '-frames'       , 0,
        '-identify',
        '-really-quiet',
    );
    
    print Dumper "@mplayer_exec";
    
    my $media_info;
    
    open(MEDIA_INFO, "@mplayer_exec 2>/dev/null|") or die "Cannot exec: '@mplayer_exec'";
    
    while (<MEDIA_INFO>) {
        next unless m/^ID_/; # We only need lines with 'ID_' at the beggining.
        chomp;
        my ($key, $value) = split(/=/, $_, 2);
        
#        $var =~ s/^ID_//;
        $key = lc $key;

        print  $key ." => ". $value. "\n";
        warn $key ." exists: ".$media_info->{$key} if scalar grep {/$key/} keys %{$media_info};
        
        if (scalar grep {/$key/} keys %{$media_info}) {
            
            my @old;
            
            @old = @{$media_info->{$key}} if (ref $media_info->{$key} eq 'ARRAY');
            
            push @old, $media_info->{$key};
            
            push @old, $value;
            
#            push @{$media_info->{$key}}, @old;
        } else {
            $media_info->{$key} .= $value;# unless scalar;
        }

        
    }
    
    close(MEDIA_INFO);
    
    print Dumper $media_info;
}

sub transcode {
    # Main thing - we are starting mencoder with desired options here
    
    # Setting this will automagically reap child processes (mencoder in this case)
    $SIG{CHLD} = 'IGNORE';
    
    my $opts = shift;
    
    my @command_line;
    foreach my $o (sort keys %{$opts}) {
        push @command_line, @{$opts->{$o}};
    }
    
    print "@command_line";
    
    exec(@command_line) == 0
        or die ("$command_line[0] failed: $?");
}
sub subtitle_check {
    my $video_filename = shift;
    my $subtitle_filename;
    
    $video_filename =~ m/(.*)\.(.*)$/;
    
    foreach (@subtitle_ext) {
         $subtitle_filename = $1.".".$_ if (-e $1.".".$_);
    }
    
    return $subtitle_filename;
}
sub generate_options {
    my $prefs = shift;
    
    my $opts = {
        # This "1_" is a HACK for proper handling of options -> first option always need to be an mencoder_path! 
        '1_command'   => [
            $prefs->{'mencoder_path'}
        ],
        'input'         => [
            $prefs->{'file_input'}
        ],
        'output_format' => [
            '-of'               , $prefs->{'output_format'},
            '-mpegopts'         , $prefs->{'output_options'},
            '-ofps'             , $prefs->{'video_framerate'},
            '-o'                , $prefs->{'file_output'}
        ],
        'subtitle'  => [
            '-ass',
            '-embeddedfonts',
            '-ass-line-spacing' , 0,
            '-ass-font-scale'   , 1,
            '-subcp'            , $prefs->{'subtitle_codepage'},
            '-subpos'           , 100,
            '-sub-fuzziness'    , 1,
#             '-font'            , $prefs->{'subtitle_fontpath'},
#             '-sid'             , 0,
        ],
        'video_codec'   => [
            '-ovc'              , 'lavc',
            '-lavcopts'         , 'vcodec='.$prefs->{'video_codec'}.':vrc_buf_size=1835:keyint=15:vrc_maxrate=9800:vbitrate='.$prefs->{'video_bitrate'}.':threads='.$prefs->{'mencoder_threads'},
        ],
        'audio_codec'   => [
            '-oac'              , $prefs->{'audio_codec'}
        ],
        'video_filter'  => [
            '-vf'               , 'expand=osd=1'
        ],
        'additional_options' => [ split { },$prefs->{'additional_options'} ] 
    };
    
    my $subtitle_filename = subtitle_check($prefs->{'file_input'});
    
    push @{$opts->{'subtitle'}}, ('-sub'        , $subtitle_filename)               if ($subtitle_filename);
    push @{$opts->{'subtitle'}}, ('-ass-styles' , $prefs->{'subtitle_ass_style'})   if ($prefs->{'subtitle_ass_style'}); 
    
    return $opts;   
}
